<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\URL;
use App\Models\Action_log;
//use Route,URL,Auth;

class AuthenticateAdmin
{

    protected $except = [
        'admin/index'
    ];

    /**
     * Handle an incoming request.
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $path_arr = explode('/', URL::getRequest()->path());
        //dd($path_arr);
        //如果是超级管理员即数据库id为1跳过
        /*if(Auth::id() === 1){
            return $next($request);
        }*/
        //纪录除超级管理员外的每个用户的操作
        if(Auth::id() != 1){
            $data = [];
            $data['admin_id'] = Auth::id();
            $data['action'] = Route::currentRouteName();
            if($request->id){
                $data['action_id'] = $request->id;
            }
            Action_log::create($data);
        }

       //如果是系统后台首页 直接跳过
       if(URL::getRequest()->path() == 'admin/index'){
           return $next($request);
       }
        //var_dump($request->route()->getAction());
        //根据路由名称，用gate检验用户权限
        $previousUrl = URL::previous();
        if(!Gate::check(Route::currentRouteName())) {
            if($request->ajax() && ($request->getMethod() != 'GET')) {
                return response()->json([
                    'status' => -1,
                    'code' => 403,
                    'msg' => '您没有权限执行此操作'
                ]);
            } else {
                return response()->view('admin.errors.403', compact('previousUrl'));
            }
        }

        return $next($request);
    }
}
